<?php
namespace Admin\Model;

use Think\Model;

class AdminModel extends Model
{
    protected $connection = 'XYC';
    protected $trueTableName = 'shopkeeper';
    protected $updateFields=array('mobile','email','qq','rid');
    protected $_validate=array(
        array('shop_idenfier','require','商户号不能为空'),
        array('merchant_name','require','商户名称不能为空'),
        array('account','require','账号不能为空'),
        array('account','check_account','该账号已存在','0','callback'),
        array('password',"/^(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@]+$).{6,}/",'密码必须包含数字、字母、特殊符号其中两种，且不可少于6位'),
        array('mobile',"/[1][3,4,5,7,8][0-9]\d{8}/",'手机号格式有误'),
        array('email','email','邮箱格式有误','2'),
        array('qq',"/\d{5,15}/",'QQ号格式有误','2'),
        array('rid','require','角色不能为空')
    );

    /**
     * 检查该商户下的账号是否已存在
     * @param string $account 账号
     * @return bool
     */
    public function check_account($account){
        $msg=$this->WHERE(['shop_idenfier'=>$_SESSION['shop_identifier'],'account'=>$account])->getField('id');
        if(!empty($msg)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 修改管理员状态
     * @param $id
     * @param int $status 修改后的状态,1正常，2禁止，-1删除
     * @return boolean|string
     */
    public function set_status($id,$status){
        $msg=$this->WHERE(['id'=>$id,'shop_idenfier'=>$_SESSION['shop_identifier']])->FIND();
        if($status==$msg['state'] || empty($msg)){
            return '状态异常，无法修改';
        }
        $res=$this->WHERE(['id'=>$id,'shop_idenfier'=>$_SESSION['shop_identifier']])->setField('state',$status);
        if($res!==false){
            if($msg['rid']=='4'){
                if(!empty(D('Communication')->WHERE(['shop_id'=>$msg['id']])->getField('id'))){
                    $res=D('Communication')->WHERE(['shop_id'=>$msg['id']])->setField('commun_state',$status);
                    if($res===false){
                        return '系统异常，请联系管理员.';
                    }
                }
            }
            return $msg;
        }else{
            return '系统异常，请联系管理员';
        }
    }

    /**
     * 重置登录密码
     * @param $id
     * @return bool|string
     */
    public function reset_pwd($id){
        $msg=$this->WHERE(['id'=>$id,'shop_idenfier'=>$_SESSION['shop_identifier']])->FIND();
        if(empty($msg)){
            return '当前状态异常，无法操作';
        }
        $res=$this->WHERE(['id'=>$id,'shop_idenfier'=>$_SESSION['shop_identifier']])->setField('password',set_pwd($msg['account'],'A123456'));
        if($res!==false){
            return $msg;
        }else{
            return '系统错误，请联系管理员';
        }
    }


    //判断用户名和密码是否正确
    public function check_login($account, $pwd)
    {
//        $admin = $this->getByaccount($account);
        $admin = M('shopkeeper','','XYC')->where(['account'=>$account])->find();
        //v2检测
        $is_v2=M('merchant','','XYC')->where(['shop_identifier'=>$admin['shop_idenfier']])->getfield('version');
        if($is_v2!='2'){
            return '该账户无法登陆本系统';
        }

//        var_dump($admin);
        if (!empty($admin)) {
            if ($admin['password'] == $pwd) {
                if($admin['state'] == '1'){
                    return $admin;
                }else{
                    return '该账户已被锁定';
                }
            } else {
                return '密码或者账号有误';
            }
        } else {
            return '密码或者账号有误.';
        }
    }

    //修改密码判断
    public function check_modify_pwd($old_pwd, $new_pwd)
    {
        $msg =$this->WHERE(['account'=>$_SESSION['account'],'shop_idenfier'=>$_SESSION['shop_identifier']])->FIND();

        if (!empty($msg)) {
            switch($msg){
                case $msg['password']!=set_pwd($msg['account'],$old_pwd):
                    return '原密码错误';
                case $old_pwd==$new_pwd:
                    return '原密码不可与新密码相同';
                case $a=preg_match("/[A-Z]+.{6,18}/",$new_pwd):
                    if(!$a){
                        return '密码必须以大写字母开头并且在6位以上';
                    }else{
                        break;
                    }
                default:
                    break;
            }
            $res=$this->WHERE(['account'=>$_SESSION['account'],'shop_idenfier'=>$_SESSION['shop_identifier']])->setField('password',set_pwd($msg['account'],$new_pwd));
            if($res!==false){
                return $msg;
            }else{
                return '系统错误，请联系管理员';
            }
        } else {
            return '登录超时，请重新登录';
        }
    }

    public function kefu_handle($data){
        $db=D('Communication');
        $res=$db->WHERE(['shop_identifier'=>$_SESSION['shop_identifier'],'shop_id'=>$data['id']])->FIND();
        if(!empty($res)){
            $db->WHERE(['shop_identifier'=>$_SESSION['shop_identifier'],'shop_id'=>$data['id']])->SAVE(['qq'=>$data['qq'],'nickname'=>$data['nickname']]);
        }else{
            $db->add([
                'shop_identifier'=>$_SESSION['shop_identifier'],
                'account'=>$data['account'],
                'shop_id'=>$data['id'],
                'qq'=>$data['qq'],
                'nickname'=>$data['nickname'],
                'ctime'=>time()
            ]);
        }
    }


    protected function _before_insert(&$data,$option){
        $merchant_db=D('Merchant');
        $data['password']=set_pwd($data['account'],$data['password']);
        $data['merchant_name']=$merchant_db->WHERE(['shop_identifier'=>$data['shop_idenfier']])->getField('merchant_name');
        $data['parent_id']=$this->WHERE(['shop_idenfier'=>$data['shop_idenfier'],'parent_id'=>'0'])->getField('id');
    }

    protected function _after_insert($data,$option){
        $shopkeeper_role_db=D('ShopkeeperRole');
        $rid=explode(',',$data['rid']);
        foreach($rid as $k=>$v){
            $role['shop_identifier']=$_SESSION['shop_identifier'];
            $role['sid']=$data['id'];
            $role['rid']=$v;
            $role['type']='2';
            $shopkeeper_role_db->add($role);
        }
    }

    protected function _before_update($data,$option){
        $shopkeeper_role_db=D('ShopkeeperRole');
        $old_rid=$this->WHERE(['id'=>$option['where']['id']])->getField('rid');
        $new_rid=explode(',',$data['rid']);
        $old_rid=explode(',',$old_rid);
        $new_role=array_diff($new_rid,$old_rid);//新增角色
        $del_role=array_diff($old_rid,$new_rid);//删除角色
        if(!empty($data['rid'])){
            if(!empty($new_role)){
                foreach($new_role as $k=>$v){
                    $role['shop_identifier']=$_SESSION['shop_identifier'];
                    $role['sid']=$option['where']['id'];
                    $role['rid']=$v;
                    $role['type']='2';
                    $shopkeeper_role_db->add($role);
                }
            }
            if(!empty($del_role)){
                foreach($del_role as $k=>$v){
                    $shopkeeper_role_db->WHERE(['sid'=>$option['where']['id'],'rid'=>$v,'shop_identifier'=>$_SESSION['shop_identifier']])->delete();
                }
            }
        }
    }

}